<template>
  <div class="home-container">
    <!-- 标签栏 -->
    <div class="category-tabs">
      <div class="tabs-wrapper">
        <div class="tabs-container">
          <CategoryTab
            v-for="category in sortedShowCategories"
            :key="category.id"
            :category="category"
            :isActive="activeCategory?.id === category.id"
            @click="setActiveCategory"
            @dragstart="onDragStart"
            @drop="onDrop"
            @hide="hideCategory"
            @update="updateCategory"
          />
        </div>
        <!-- 移动端更多菜单按钮 -->
        <div class="more-menu-button" v-if="isMobile" @click="showMoreMenu = !showMoreMenu">
          <div class="dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
          <!-- 下拉菜单 -->
          <div class="dropdown-menu" v-if="showMoreMenu">
            <div class="menu-item" @click="handleAllCategories">
              <span>全部标签</span>
            </div>
            <div class="menu-item" @click="handleAddCategory">
              <span>添加标签</span>
            </div>
          </div>
        </div>
      </div>
      <div class="action-buttons" v-if="!isMobile">
        <button class="all-categories-btn" @click="showAllCategoriesModal = true">
          <span>全部标签</span>
        </button>
        <button class="add-category-btn" @click="showAddCategoryModal = true">
          <span class="add-icon">+</span>
          <span class="add-text">添加标签</span>
        </button>
      </div>
    </div>

    <!-- 全部标签模态框 -->
    <div
      class="modal-overlay"
      v-if="showAllCategoriesModal"
      @click="showAllCategoriesModal = false"
    >
      <div class="modal-content" @click.stop>
        <h3 class="modal-title">全部标签</h3>
        <div class="modal-body">
          <div class="categories-list">
            <div v-for="category in allCategories" :key="category.id" class="category-item">
              <span class="category-name">{{ category.name }}</span>
              <div class="category-actions">
                <button class="action-btn" @click="toggleCategoryVisibility(category)">
                  <SvgIcon
                    v-if="isCategoryVisible(category)"
                    name="eye-open"
                    width="20"
                    height="20"
                  />
                  <SvgIcon v-else name="eye-close" width="20" height="20" />
                </button>
                <button class="action-btn delete" @click="deleteCategory(category.id)">
                  <SvgIcon name="delete" width="20" height="20" />
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="showAllCategoriesModal = false">确定</button>
        </div>
      </div>
    </div>

    <!-- 添加标签模态框 -->
    <div class="modal-overlay" v-if="showAddCategoryModal" @click="showAddCategoryModal = false">
      <div class="modal-content" @click.stop>
        <h3 class="modal-title">添加新标签</h3>
        <div class="modal-body">
          <div class="form-group">
            <label for="categoryName">标签名称</label>
            <input
              type="text"
              id="categoryName"
              v-model="newCategoryName"
              placeholder="请输入标签名称"
              @keyup.enter="addCategory"
            />
          </div>
          <div class="form-group">
            <label for="categoryColor">标签颜色</label>
            <div class="color-picker-container">
              <input
                type="color"
                id="categoryColor"
                v-model="newCategoryColor"
                class="color-picker"
              />
              <div class="color-preview" :style="{ backgroundColor: newCategoryColor }"></div>
              <span class="color-code">{{ newCategoryColor }}</span>
            </div>

            <!-- 颜色快捷选择网格 -->
            <div class="color-grid">
              <div
                v-for="color in predefinedColors"
                :key="color"
                class="color-option"
                :style="{ backgroundColor: color }"
                :class="{ active: newCategoryColor === color }"
                @click="newCategoryColor = color"
                :title="color"
              ></div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showAddCategoryModal = false">取消</button>
          <button class="confirm-btn" @click="addCategory" :disabled="!canAddCategory">确认</button>
        </div>
      </div>
    </div>

    <!-- 待办事项列表区域 -->
    <div class="todo-lists-wrapper">
      <div class="todo-lists-container" :class="`columns-${columnsCount}`">
        <TodoList
          v-for="category in visibleCategories"
          :key="category.id"
          :category="category"
          :todos="category.id === 'completed' ? [] : todosByCategory[category.id] || []"
          :allTodos="todos"
          :allCategories="allCategories.value"
          @toggle="toggleTodo"
          @update="updateTodo"
          @reorder="handleReorder"
        />
      </div>
    </div>

    <!-- 修改分页指示器，添加导航按钮 -->
    <div v-if="totalPages > 1" class="pagination-container">
      <button class="pagination-nav-btn" :class="{ disabled: currentPage === 0 }" @click="prevPage">
        <svg viewBox="0 0 24 24" width="20" height="20">
          <path fill="currentColor" d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
        </svg>
      </button>
      <div class="pagination-dots">
        <span
          v-for="page in totalPages"
          :key="page"
          class="pagination-dot"
          :class="{ active: page - 1 === currentPage }"
          @click="goToPage(page - 1)"
        ></span>
      </div>
      <button class="pagination-nav-btn" :class="{ disabled: !hasMorePages }" @click="nextPage">
        <svg viewBox="0 0 24 24" width="20" height="20">
          <path fill="currentColor" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
        </svg>
      </button>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, provide, onUnmounted } from 'vue'
import CategoryTab from '@/components/CategoryTab.vue'
import TodoList from '@/components/TodoList.vue'
import SvgIcon from '@/components/SvgIcon.vue'
import {
  createLabel,
  removeLabel,
  getAllLabels,
  getShownLabels,
  addShowLabel,
  updateShowSortLabels,
  updateLabel,
} from '@/api/label'
import { getShownTodos, updateTodo as updateTodoAPI, createTodo } from '@/api/todo'

// 直接在组件中维护状态
const allCategories = ref([]) // 所有标签
const showCategories = ref([]) // 显示的标签
const todos = ref([]) // 所有待办事项
const activeCategory = ref(null) // 当前激活的标签

// 用于强制刷新 todosByCategory
const forceUpdateKey = ref(0)
const refreshTodosByCategory = () => {
  forceUpdateKey.value++
}

// 完全重新加载所有数据
const reloadAllData = async (preserveActive = true) => {
  const currentActiveId = activeCategory.value?.id

  try {
    await fetchLabels()
    await fetchShownLabels()
    await fetchTodos()

    refreshTodosByCategory()
    forceUpdateVisibleCategories()

    if (preserveActive && currentActiveId) {
      const targetCategory = showCategories.value.find((cat) => cat.id === currentActiveId)
      if (targetCategory) {
        activeCategory.value = targetCategory
      } else {
        if (showCategories.value.length > 0) {
          activeCategory.value = showCategories.value[0]
        }
      }
    }
    return true
  } catch (error) {
    console.error('重新加载数据失败:', error)
    return false
  }
}

// 计算属性：将待办事项按分类分组
const todosByCategory = computed(() => {
  console.log(
    'todosByCategory 重新计算中，todos数量:',
    todos.value.length,
    '刷新标记:',
    forceUpdateKey.value,
  )

  // 创建一个新对象，确保每次计算返回新的引用
  const newResult = {}

  todos.value.forEach((todo) => {
    if (!todo.completed) {
      if (!newResult[todo.labelId]) {
        newResult[todo.labelId] = []
      }
      // 为每个待办创建一个新对象，以确保响应式更新
      newResult[todo.labelId].push({ ...todo })
    }
  })

  // 返回新对象，确保 Vue 的响应式系统能检测到变化
  return newResult
})

// 计算属性：已排序的展示标签
const sortedShowCategories = computed(() => {
  return [...showCategories.value].sort((a, b) => a.order - b.order)
})

// 获取所有标签
const fetchLabels = async () => {
  try {
    const result = await getAllLabels()
    if (result.success) {
      allCategories.value = result.data.map((label) => ({
        id: label.id,
        name: label.name,
        color: label.color || '#4361ee',
        order: 0,
      }))
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 获取展示的标签
const fetchShownLabels = async () => {
  try {
    const result = await getShownLabels()
    if (result.success) {
      showCategories.value = result.data.map((label, index) => ({
        id: label.id,
        name: label.name,
        color: label.color || '#4361ee',
        order: index,
      }))

      if (showCategories.value.length > 0) {
        activeCategory.value = showCategories.value[0]
      }
    }
  } catch (error) {
    console.error('获取展示标签失败:', error)
  }
}

// 获取未完成的待办事项列表
const fetchTodos = async () => {
  try {
    const result = await getShownTodos()
    if (result.success) {
      const newTodos = []

      result.data.forEach((group) => {
        group.todoItems.forEach((item) => {
          newTodos.push({
            id: item.todoItemId,
            content: item.content,
            labelId: group.labelId,
            labelName: group.labelName,
            completed: false,
            createdAt: item.createdAt,
            updatedAt: item.updatedAt,
          })
        })
      })

      todos.value = newTodos
    }
  } catch (error) {
    console.error('获取待办事项列表失败:', error)
  }
}

// 分页相关状态
const currentPage = ref(0)
// 根据屏幕宽度动态设置每页显示的列表数量
const itemsPerPage = ref(3) // 默认每页显示3个列表

// 监听窗口大小变化，调整每页显示数量
const updateItemsPerPage = () => {
  if (window.innerWidth <= 768) {
    itemsPerPage.value = 1 // 移动端一页只显示1个
  } else if (window.innerWidth <= 1200) {
    itemsPerPage.value = 2 // 平板设备一页显示2个
  } else {
    itemsPerPage.value = 3 // 桌面设备一页显示3个
  }
}

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(sortedShowCategories.value.length / itemsPerPage.value)
})

// 判断是否有更多页
const hasMorePages = computed(() => {
  return currentPage.value < totalPages.value - 1
})

// 计算当前页显示的列数
const columnsCount = computed(() => {
  const remainingItems = sortedShowCategories.value.length - currentPage.value * itemsPerPage.value
  return Math.min(remainingItems, itemsPerPage.value)
})

// 获取当前页可见的分类
const visibleCategoriesUpdateKey = ref(0)
const forceUpdateVisibleCategories = () => {
  visibleCategoriesUpdateKey.value++
}

// 获取当前页可见的分类
const visibleCategories = computed(() => {
  const start = currentPage.value * itemsPerPage.value
  const end = start + itemsPerPage.value
  const visibleCats = sortedShowCategories.value.slice(start, end)

  // 返回结果时创建新的数组引用，确保响应式更新
  return [...visibleCats]
})

// 翻页方法
const nextPage = () => {
  if (hasMorePages.value) {
    currentPage.value++
  }
}

const prevPage = () => {
  if (currentPage.value > 0) {
    currentPage.value--
  }
}

const goToPage = (page) => {
  if (page >= 0 && page < totalPages.value) {
    currentPage.value = page
  }
}

// 设置激活的分类
const setActiveCategory = (categoryId) => {
  activeCategory.value = showCategories.value.find((cat) => cat.id === categoryId) || null

  // 自动切换到包含该分类的页面
  const categoryIndex = sortedShowCategories.value.findIndex((cat) => cat.id === categoryId)
  if (categoryIndex !== -1) {
    const targetPage = Math.floor(categoryIndex / itemsPerPage.value)
    currentPage.value = targetPage
  }
}

// 切换待办事项完成状态
const toggleTodo = async (todoId) => {
  try {
    // 先找到待办事项对象
    const todo = todos.value.find((t) => t.id === todoId)
    if (!todo) return

    // 准备API参数
    const updatedData = {
      id: todoId,
      isCompleted: !todo.completed,
      labels: [todo.labelId], // 使用labelId创建数组
      content: todo.content,
    }

    // 调用API更新待办状态
    const result = await updateTodoAPI(updatedData)

    if (result.success) {
      // API成功后，在本地更新待办状态
      todo.completed = !todo.completed

      // 如果设置为已完成，可能需要重新获取待办列表
      if (updatedData.isCompleted) {
        await fetchTodos()
      }
    } else {
      console.error('更新待办事项状态失败：', result.msg)
    }
  } catch (error) {
    console.error('更新待办事项状态出错：', error)
  }
}

// 添加更新待办事项方法
const updateTodo = async ({ id, content }) => {
  try {
    // 先找到待办事项对象
    const todo = todos.value.find((t) => getTodoId(t) === id)
    if (!todo) return

    // 准备API参数
    const updatedData = {
      id,
      content,
      isCompleted: todo.completed,
      labels: [todo.labelId],
    }

    // 调用API更新
    const result = await updateTodoAPI(updatedData)

    if (result.success) {
      // API成功后，在本地更新待办内容
      todo.content = content
    } else {
      console.error('更新待办内容失败：', result.msg)
    }
  } catch (error) {
    console.error('更新待办内容出错：', error)
  }
}

// 处理待办项重新排序
const handleReorder = (data) => {
  const { labelId, todos: reorderedTodos } = data

  // 更新原始待办数组中该分类下的所有待办项
  // 1. 先从todos中找出不属于当前分类的项目
  const otherTodos = todos.value.filter((todo) => todo.labelId !== labelId || todo.completed)

  // 2. 合并不变的项目和重新排序后的项目
  todos.value = [...otherTodos, ...reorderedTodos]

  // 3. 强制刷新计算属性
  refreshTodosByCategory()
}

// 获取待办项的ID（兼容不同的数据结构）
const getTodoId = (todo) => {
  return todo.todoItemId || todo.id
}

// 删除标签
const deleteCategory = async (categoryId) => {
  try {
    const result = await removeLabel({ id: categoryId })
    if (result.success) {
      // 从本地标签列表中移除
      allCategories.value = allCategories.value.filter((cat) => cat.id !== categoryId)

      // 如果该标签在显示列表中，也从显示列表中移除
      const showIndex = showCategories.value.findIndex((cat) => cat.id === categoryId)
      if (showIndex !== -1) {
        showCategories.value.splice(showIndex, 1)
      }

      // 如果当前页没有内容了，则返回上一页
      if (visibleCategories.value.length === 0 && currentPage.value > 0) {
        currentPage.value--
      }
    } else {
      console.error('标签删除失败：', result.msg)
    }
  } catch (error) {
    console.error('标签删除失败：', error)
  }
}

// 隐藏标签
const hideCategory = async (categoryId) => {
  try {
    // 先从本地显示列表中移除
    const index = showCategories.value.findIndex((cat) => cat.id === categoryId)
    if (index !== -1) {
      showCategories.value.splice(index, 1)
    }

    // 获取剩余标签的ID数组，按照顺序排列
    const showCategoryIds = sortedShowCategories.value.map((cat) => cat.id)

    // 调用API更新展示标签排序
    const result = await updateShowSortLabels(showCategoryIds)

    if (!result.success) {
      console.error('隐藏标签失败：', result.msg)
      // 如果API调用失败，重新获取数据
      await fetchShownLabels()
    }

    // 如果当前页没有内容了，则返回上一页
    if (visibleCategories.value.length === 0 && currentPage.value > 0) {
      currentPage.value--
    }
  } catch (error) {
    console.error('隐藏标签失败：', error)
    await fetchShownLabels()
  }
}

// 拖拽开始
const onDragStart = ({ event, categoryId }) => {
  event.dataTransfer.setData('categoryId', categoryId)
}

// 放置处理
const onDrop = async ({ event, categoryId }) => {
  // 从dataTransfer获取拖拽的分类ID
  const draggedCategoryIdStr = event.dataTransfer.getData('categoryId')
  // 保留原始类型 - 字符串或数字
  const draggedCategoryId = draggedCategoryIdStr

  if (draggedCategoryId !== categoryId) {
    const newOrder = [...sortedShowCategories.value]
    const draggedIndex = newOrder.findIndex((cat) => cat.id === draggedCategoryId)
    const targetIndex = newOrder.findIndex((cat) => cat.id === categoryId)

    // 重新排序
    const [removed] = newOrder.splice(draggedIndex, 1)
    newOrder.splice(targetIndex, 0, removed)

    // 更新顺序 - 先在本地更新
    showCategories.value.forEach((cat) => {
      const newIndex = newOrder.findIndex((c) => c.id === cat.id)
      if (newIndex !== -1) {
        cat.order = newIndex
      }
    })

    // 调用API更新排序
    try {
      const result = await updateShowSortLabels(newOrder.map((cat) => cat.id))
      if (!result.success) {
        console.error('更新标签排序失败：', result.msg)
        await fetchShownLabels() // 如果失败，重新获取标签数据
      }
    } catch (error) {
      console.error('更新标签排序失败：', error)
      await fetchShownLabels() // 如果失败，重新获取标签数据
    }
  }
}

// 添加分类相关状态
const showAddCategoryModal = ref(false)
const newCategoryName = ref('')
const newCategoryColor = ref('#4361ee') // 默认颜色

// 预定义颜色列表
const predefinedColors = [
  // 行1: 红色系
  '#FF3B30',
  '#FF9500',
  '#FFCC00',
  '#FFD60A',
  '#FFC0CB',
  '#FF69B4',
  // 行2: 绿色系
  '#4CD964',
  '#34C759',
  '#32D74B',
  '#00BFA5',
  '#5AC8FA',
  '#3DDC84',
  // 行3: 蓝色系
  '#007AFF',
  '#5856D6',
  '#4361EE',
  '#0A84FF',
  '#64D2FF',
  '#00CCFF',
  // 行4: 其他亮色
  '#BF5AF2',
  '#FF2D55',
  '#AF52DE',
  '#FF9966',
  '#FF6B6B',
  '#FF8A65',
  // 行5: 暖色系
  '#A2845E',
  '#8E8E93',
  '#E5E5EA',
  '#D4AF37',
  '#B87333',
  '#CD7F32',
  // 行6: 灰色和深色
  '#000000',
  '#1C1C1E',
  '#2C2C2E',
  '#3A3A3C',
  '#48484A',
  '#636366',
]

// 判断是否可以添加分类
const canAddCategory = computed(() => {
  return newCategoryName.value.trim() !== ''
})

// 添加标签
const addCategory = async () => {
  if (!canAddCategory.value) return

  try {
    const result = await createLabel({
      name: newCategoryName.value.trim(),
      color: newCategoryColor.value,
    })

    if (result.success) {
      const newCategoryId = result.data

      const newCategory = {
        id: newCategoryId,
        name: newCategoryName.value.trim(),
        color: newCategoryColor.value,
        order: allCategories.value.length,
      }

      allCategories.value.push(newCategory)

      newCategoryName.value = ''
      newCategoryColor.value = '#4361ee'
      showAddCategoryModal.value = false

      try {
        const showResult = await addShowLabel({ id: newCategoryId })
        if (showResult.success) {
          await reloadAllData(false)
          setActiveCategory(newCategoryId)
        } else {
          await reloadAllData(true)
        }
      } catch (error) {
        console.error('添加标签到显示列表失败:', error)
        await reloadAllData(true)
      }
    }
  } catch (error) {
    console.error('创建标签失败:', error)
  }
}

// 更新分类
const updateCategory = async ({ id, name, color }) => {
  try {
    // 调用API更新标签，传递颜色信息
    const updateData = { id, name }
    if (color) updateData.color = color

    const result = await updateLabel(updateData)

    if (result.success) {
      // API调用成功后，更新本地数据
      // 更新所有标签列表中的名称和颜色
      const catIndex = allCategories.value.findIndex((cat) => cat.id === id)
      if (catIndex !== -1) {
        allCategories.value[catIndex].name = name
        if (color) allCategories.value[catIndex].color = color
      }

      // 更新显示标签列表中的名称和颜色
      const showIndex = showCategories.value.findIndex((cat) => cat.id === id)
      if (showIndex !== -1) {
        showCategories.value[showIndex].name = name
        if (color) showCategories.value[showIndex].color = color
      }
    } else {
      console.error('更新标签失败：', result.msg)
    }
  } catch (error) {
    console.error('更新标签失败：', error)
  }
}

// 全部分类模态框状态
const showAllCategoriesModal = ref(false)

// 判断标签是否可见
const isCategoryVisible = (category) => {
  return showCategories.value.some((cat) => cat.id === category.id)
}

// 切换标签可见性
const toggleCategoryVisibility = async (category) => {
  if (isCategoryVisible(category)) {
    // 如果当前标签可见，则从showCategories中移除
    try {
      // 先从本地移除
      const index = showCategories.value.findIndex((cat) => cat.id === category.id)
      if (index !== -1) {
        showCategories.value.splice(index, 1)
      }

      // 获取剩余标签的ID数组，按照顺序排列
      const showCategoryIds = sortedShowCategories.value.map((cat) => cat.id)

      // 调用API更新展示标签排序
      const result = await updateShowSortLabels(showCategoryIds)

      if (!result.success) {
        console.error('取消展示标签失败：', result.msg)
        // 如果API调用失败，重新获取数据
        await fetchShownLabels()
      }
    } catch (error) {
      console.error('取消展示标签失败：', error)
      await fetchShownLabels()
    }
  } else {
    // 如果当前标签不可见，则添加到showCategories中
    try {
      // 调用API添加标签到展示列表
      const result = await addShowLabel({ id: category.id })
      if (result.success) {
        // API调用成功后，重新获取显示标签列表
        await fetchShownLabels()
      } else {
        console.error('添加标签到展示列表失败：', result.msg)
      }
    } catch (error) {
      console.error('添加标签到展示列表失败：', error)
    }
  }

  // 如果当前页没有内容了，则返回上一页
  if (visibleCategories.value.length === 0 && currentPage.value > 0) {
    currentPage.value--
  }
}

// 添加移动端检测
const isMobile = ref(false)
// 更多菜单显示状态
const showMoreMenu = ref(false)

// 检测是否为移动设备
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 在组件挂载时设置正确的每页显示数量并添加窗口大小变化监听
onMounted(async () => {
  try {
    await fetchLabels()
    await fetchShownLabels()
    await fetchTodos()

    // 设置正确的每页显示数量
    updateItemsPerPage()

    // 检测是否为移动设备
    checkMobile()

    // 添加窗口大小变化监听
    window.addEventListener('resize', () => {
      updateItemsPerPage()
      checkMobile()
    })

    window.addEventListener('refresh-todo-list', async () => {
      await reloadAllData(true)
    })

    // 点击页面其他区域关闭下拉菜单
    document.addEventListener('click', (e) => {
      if (!e.target.closest('.more-menu-button') && showMoreMenu.value) {
        showMoreMenu.value = false
      }
    })
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('refresh-todo-list', () => {})
  window.removeEventListener('resize', () => {})
  document.removeEventListener('click', () => {})
})

// 提供数据给子组件
provide(
  'categories',
  computed(() => allCategories.value),
)
provide('fetchTodos', fetchTodos)
provide('addTodo', async (content, labelIds) => {
  try {
    // 确保labelIds是数组
    const labelsArray = Array.isArray(labelIds) ? labelIds : [labelIds]

    const result = await createTodo({
      content: content.trim(),
      labels: labelsArray,
    })

    if (result.success) {
      // 直接使用全局重新加载函数，完全刷新数据
      await reloadAllData(true)

      // 确保当前标签是添加待办的标签之一（使用第一个标签）
      if (labelsArray.length > 0 && activeCategory.value?.id !== labelsArray[0]) {
        // 找到对应的显示标签
        const showCategory = showCategories.value.find((cat) => cat.id === labelsArray[0])
        if (showCategory) {
          // 将当前活动标签设置为添加待办的第一个标签
          setActiveCategory(labelsArray[0])
        }
      }

      return true
    } else {
      console.error('添加待办事项失败：', result.msg)
      return false
    }
  } catch (error) {
    console.error('添加待办事项出错：', error)
    return false
  }
})

// 处理点击全部标签
const handleAllCategories = () => {
  showAllCategoriesModal.value = true
  showMoreMenu.value = false
}

// 处理点击添加标签
const handleAddCategory = () => {
  showAddCategoryModal.value = true
  showMoreMenu.value = false
}
</script>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 分类标签栏 */
.category-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #d2d2d7;
  margin-bottom: 20px;
  padding-bottom: 15px;
  gap: 10px;
}

/* 增加一个包装容器，便于定位更多按钮 */
.tabs-wrapper {
  position: relative;
  display: flex;
  flex: 1;
  min-width: 0;
}

.tabs-container {
  display: flex;
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 5px; /* 为滚动条预留空间 */
  margin-bottom: -5px; /* 抵消padding-bottom造成的间距 */
  -webkit-overflow-scrolling: touch; /* 在iOS上提供平滑滚动 */
  scrollbar-width: thin; /* Firefox的滚动条样式 */
  scrollbar-color: #d2d2d7 transparent; /* Firefox的滚动条颜色 */
  white-space: nowrap; /* 防止内容换行 */
  scroll-behavior: smooth; /* 平滑滚动效果 */
  max-width: 100%; /* 确保不会超出父容器 */
}

/* Webkit浏览器的滚动条样式 */
.tabs-container::-webkit-scrollbar {
  height: 4px;
}

.tabs-container::-webkit-scrollbar-track {
  background: transparent;
}

.tabs-container::-webkit-scrollbar-thumb {
  background-color: #d2d2d7;
  border-radius: 2px;
}

.tabs-container::-webkit-scrollbar-thumb:hover {
  background-color: #86868b;
}

/* 确保标签不会换行 */
.tabs-container > * {
  flex-shrink: 0;
}

.add-category-btn {
  display: flex;
  align-items: center;
  background: none;
  border: 2px dashed #d2d2d7;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
  color: #86868b;
  cursor: pointer;
  transition: all 0.3s;
  flex-shrink: 0; /* 防止按钮被压缩 */
}

.add-category-btn:hover {
  border-color: #4361ee;
  color: #4361ee;
  background-color: rgba(67, 97, 238, 0.05);
}

.add-icon {
  font-size: 16px;
  margin-right: 6px;
  font-weight: bold;
}

/* 添加全部分类按钮样式 */
.all-categories-btn {
  display: flex;
  align-items: center;
  background: none;
  border: 2px solid #d2d2d7;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
  color: #86868b;
  cursor: pointer;
  transition: all 0.3s;
  flex-shrink: 0;
  margin-right: 10px;
}

.all-categories-btn:hover {
  border-color: #4361ee;
  color: #4361ee;
  background-color: rgba(67, 97, 238, 0.05);
}

/* 全部分类列表样式 */
.categories-list {
  max-height: 400px;
  overflow-y: auto;
  margin: 0 -20px;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  border-bottom: 1px solid #f5f5f7;
  transition: background-color 0.3s;
}

.category-item:hover {
  background-color: #f5f5f7;
}

.category-name {
  font-size: 14px;
  color: #1d1d1f;
  flex: 1;
}

.category-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  color: #86868b;
  transition: color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn:hover {
  color: #4361ee;
}

.action-btn.delete:hover {
  color: #ff3b30;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.modal-title {
  padding: 20px;
  border-bottom: 1px solid #f5f5f7;
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #86868b;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #d2d2d7;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #4361ee;
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
}

.modal-footer {
  padding: 15px 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid #f5f5f7;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background-color: #f5f5f7;
  color: #1d1d1f;
  border: none;
}

.cancel-btn:hover {
  background-color: #e5e5ea;
}

.confirm-btn {
  background-color: #4361ee;
  color: white;
  border: none;
}

.confirm-btn:hover {
  background-color: #3a56d4;
}

.confirm-btn:disabled {
  background-color: #d2d2d7;
  cursor: not-allowed;
}

/* 待办事项列表区域 */
.todo-lists-wrapper {
  position: relative;
  display: flex;
  align-items: flex-start;
  flex: 1;
  height: calc(100% - 100px); /* 减去顶部标签栏的高度 */
  overflow: hidden; /* 防止溢出 */
}

.todo-lists-container {
  display: grid;
  gap: 20px;
  flex: 1;
  transition: transform 0.3s ease;
  height: 100%;
  grid-auto-rows: minmax(0, 1fr); /* 修改这里，允许容器自适应高度 */
  padding-bottom: 10px;
  max-height: 100%; /* 添加最大高度限制 */
  overflow: hidden; /* 防止溢出 */
}

.todo-lists-container.columns-1 {
  grid-template-columns: 1fr;
}

.todo-lists-container.columns-2 {
  grid-template-columns: 1fr 1fr;
}

.todo-lists-container.columns-3 {
  grid-template-columns: 1fr 1fr 1fr;
}

/* 新的分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  margin-bottom: 10px;
  gap: 16px;
}

.pagination-dots {
  display: flex;
  gap: 8px;
}

.pagination-nav-btn {
  width: 32px;
  height: 32px;
  border-radius: 16px;
  background-color: white;
  border: 1px solid #d2d2d7;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #4361ee;
  transition: all 0.3s;
}

.pagination-nav-btn:hover:not(.disabled) {
  background-color: #4361ee;
  color: white;
  border-color: #4361ee;
}

.pagination-nav-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: #86868b;
}

/* 修改分页点的样式以匹配新设计 */
.pagination-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #d2d2d7;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-dot.active {
  background-color: #4361ee;
  transform: scale(1.2);
}

.pagination-dot:hover:not(.active) {
  background-color: #86868b;
}

@media (max-width: 1200px) {
  .todo-lists-container.columns-3 {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 768px) {
  .todo-lists-container.columns-2,
  .todo-lists-container.columns-3 {
    grid-template-columns: 1fr;
  }

  .todo-lists-container {
    padding: 0;
  }

  .todo-lists-wrapper {
    height: auto; /* 移除高度限制，使其自适应内容 */
    min-height: 0; /* 移除最小高度限制 */
    overflow-y: visible; /* 允许内容自然流动 */
  }

  .category-tabs {
    flex-direction: column;
    align-items: flex-start;
    overflow: visible; /* 确保不会截断内部滚动容器 */
    width: 100%; /* 确保在移动端占满宽度 */
  }

  /* 让tabs-wrapper在移动端占满宽度 */
  .tabs-wrapper {
    width: 100%;
  }

  .tabs-container {
    width: calc(100% - 48px); /* 减去更多按钮的宽度和间距 */
    overflow-x: scroll; /* 强制显示滚动，即使在某些移动设备上 */
    -webkit-overflow-scrolling: touch; /* 增强移动端滚动体验 */
    margin-bottom: 0;
    position: relative; /* 相对定位以便内容可以溢出 */
    touch-action: pan-x; /* 明确支持水平滑动 */
    padding-bottom: 0;
  }

  /* 隐藏移动端滚动条但保留功能 */
  .tabs-container::-webkit-scrollbar {
    display: none; /* 隐藏滚动条但保留滚动功能 */
  }
  .tabs-container {
    scrollbar-width: none; /* Firefox隐藏滚动条 */
    -ms-overflow-style: none; /* IE/Edge隐藏滚动条 */
  }

  /* 增强移动端标签项的样式，使其更容易点击 */
  .tabs-container > * {
    padding: 0 5px; /* 增加标签项的内边距，使其更易点击 */
  }

  /* 移动端隐藏原操作按钮 */
  .action-buttons {
    display: none;
  }

  /* 增强移动端分页样式 */
  .pagination-container {
    margin-top: 15px;
    padding: 5px 0;
  }

  .pagination-dot {
    width: 10px;
    height: 10px;
  }

  .pagination-nav-btn {
    width: 40px;
    height: 40px;
  }
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

/* 颜色选择器样式 */
.color-picker-container {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 15px;
}

.color-picker {
  width: 50px;
  height: 40px;
  border: none;
  padding: 0;
  background: transparent;
  cursor: pointer;
}

.color-preview {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  border: 1px solid #d2d2d7;
}

.color-code {
  font-size: 14px;
  color: #86868b;
  flex: 1;
}

/* 颜色网格样式 */
.color-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 5px;
  margin-top: 10px;
}

.color-option {
  width: 100%;
  aspect-ratio: 1/1;
  max-width: 30px;
  max-height: 30px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #d2d2d7;
  margin: 0 auto;
}

.color-option:hover {
  transform: scale(1.08);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.color-option.active {
  transform: scale(1.05);
  box-shadow:
    0 0 0 2px #fff,
    0 0 0 3px #4361ee;
}

/* 移动端更多菜单按钮样式 */
.more-menu-button {
  position: relative;
  width: 40px;
  min-width: 40px;
  height: 40px;
  border-radius: 20px;
  background-color: #f5f5f7;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 8px;
  z-index: 5;
}

.more-menu-button .dots {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 3px;
}

.more-menu-button .dots span {
  display: block;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #86868b;
}

/* 下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 45px;
  right: 0;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 150px;
  z-index: 10;
  overflow: hidden;
}

.menu-item {
  padding: 12px 16px;
  font-size: 14px;
  color: #1d1d1f;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #f5f5f7;
}

.menu-item:not(:last-child) {
  border-bottom: 1px solid #f5f5f7;
}
</style>
